﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using STX.Admin.Models.BizMaterialCategory;
using STX.Service;
using STX.Domain;
using STX.Web.Framework;
namespace STX.Admin.Controllers
{
    public class BizMaterialCategoryController : BasePages1Controller<BizMaterialCategory, IndexModel, AddModel, EditModel, QueryModel>
    {
        public BizMaterialCategoryService BizMaterialCategoryService { get; set; }

        protected override void OnInit(out Func<BaseService<BizMaterialCategory>> thiService, out Func<IndexModel> getIndexModelFunc, out Func<AddModel> getAddModelFunc, out Func<int, EditModel> getEditModelFunc)
        {
            thiService = () => BizMaterialCategoryService;
            getIndexModelFunc = ()=> new IndexModel();
            getAddModelFunc = ()=> new AddModel();
            getEditModelFunc = id =>
            {
                var model = BizMaterialCategoryService.FindModelById(id);
                if (model == null)
                {
                    throw  new Exception("此条数据可能已被删除");
                }
                return new EditModel()
                {
                    Name = model.Name,
                    Id = id,
                    Type = (int)model.Type,
                    Code = model.Code
                };
            };
        }

        protected override long AddHandler(AddModel addModel)
        {
            var model = new BizMaterialCategory()
            {
                Name = addModel.Name,
                Code = addModel.Code,
                Type = (BizMaterialCategory.TypeEnum) addModel.Type
            };
            return BizMaterialCategoryService.Add(model);
        }


        protected override bool EditHandler(EditModel editModel)
        {
            var model = BizMaterialCategoryService.FindModelById(editModel.Id);
            if (model == null)
            {
                throw new Exception("此条数据可能已被删除");
            }
            model.Code = editModel.Code;
            model.Name = editModel.Name;
            model.Type = (BizMaterialCategory.TypeEnum) editModel.Type;
            BizMaterialCategoryService.Update(model);
            return true;
        }

        protected override IQueryable<BizMaterialCategory> OrderByHandler(IQueryable<BizMaterialCategory> queryable)
        {
            return queryable.OrderBy(o => o.Code);
        }

        protected override IQueryable<BizMaterialCategory> QueryHandler(QueryModel queryModel, IQueryable<BizMaterialCategory> queryable)
        {
            return queryable;
        }

        public override JsonResult Delete(int[] ids)
        {
            throw new Exception("物料分类不能删除");
        }
    }
}
